const db=require('../db/index')
const bcrypt=require('bcryptjs')
const jwt=require('jsonwebtoken')
const config=require('../config')
exports.login=(req,res)=>{
   db.query('select * from users where phone=?',req.body.phone,(err,result)=>{
    if(err){
        return req.resSend(401,err)
    }
    if(result.length===0){
        return req.resSend(404,'用户名输入错误！')
    }
    const compareResult=bcrypt.compareSync(req.body.password,result[0].password)
    if(!compareResult){
        return req.resSend(401,'密码输入错误！')
    }
    const user={...result[0],password:'',phone:'',}
    const token=jwt.sign(user,config.secretKey,{expiresIn:config.expiresIn})
    console.log(token)
    res.send({
        status:200,
        msg:'登录成功！',
        token:'Bearer '+token
    })
   })
}

exports.register=(req,res)=>{
    console.log(req.body)
  db.query('select * from users where phone=?',req.body.phone,(err,result)=>{
    if(err){
        return req.resSend(401,err)
    }
    if(result.length!==0){
        return req.resSend(404,'该手机号已经被注册！')
    }
    const userInfo={}
    userInfo.username=req.body.username
    userInfo.phone=req.body.phone
    userInfo.password=bcrypt.hashSync(req.body.password,10)
    db.query('insert into users set ?',userInfo,(err,result)=>{
        if(err){
            return req.resSend(401,err)
        }
        if(result.affectedRows!==1){
            return req.resSend(404,'用户注册失败！')
        }
        req.resSend(200,'用户注册成功！')
    })
  })
}